# -*- coding = utf-8 -*-
# @Time: 2024/08/02 09:15
# @Author: Bobby
# @File: port.py
# @Software: PyCharm


import requests
import os

l_url = 'http://192.168.126.137:8080'


class Port:
    def login(self, l_data):
        l_path = '/v7/login'
        header = {'Content-Type': 'application/json;charset=UTF-8'}
        r = requests.post(url=l_url + l_path, json=l_data, headers=header)
        r.encoding = 'UTF-8'
        c = r.status_code
        r = r.json()
        if 'user' in r and 'loginname' in r['user']:
            result = r['user']['loginname']
        else:
            result = r['status']
        return c, r, result

    def add_person(self, l_data, p_data):
        p_path = '/pimpeople'
        auth = {"Authorization": f"Bearer {self.login(l_data)[1]['token']}"}
        r = requests.post(url=l_url + p_path, json=p_data, headers=auth)
        r.encoding = 'UTF-8'
        c = r.status_code
        r = r.json()
        if 'createman' in r:
            result = r['createman']
        else:
            result = r['status']
        return c, r, result

    def add_top(self, file_path):
        top_path = '/ibizutil/upload'
        file_path = f'{file_path}'
        fileName = os.path.basename(file_path)
        files = {'file': (f'{fileName}', open(file_path, 'rb'), 'image/jpeg')}
        r = requests.post(url=l_url + top_path, files=files)
        r.encoding = 'UTF-8'
        c = r.status_code
        r = r.json()
        if 'name' in r:
            result = r['name']
        else:
            result = r['status']
        return c, r, result

    def save_person(self, l_data, p_data, s_data):
        s_path = f'/pimpeople/{self.add_person(l_data, p_data)[1]["pimpersonid"]}'
        s_data['pimpersonid'] = self.add_person(l_data, p_data)[1]["pimpersonid"]
        auth = {"Authorization": f"Bearer {self.login(l_data)[1]['token']}"}
        r = requests.put(url=l_url + s_path, json=s_data, headers=auth)
        r.encoding = 'UTF-8'
        c = r.status_code
        r = r.json()
        if 'createman' in r:
            result = r['createman']
        else:
            result = r['status']
        return c, r, result
